<style>
    #detailModal h4 {
        font-weight: 700;
        display: inline-block;
    }
    
    #detailModal .detailModal-form {
        display: inline-block;
        font-family: 'Courier New', Courier, monospace;
        color: gray;
    }
    
    #detailModal .detailModal-icon {
        position: absolute;
        right: 15%;
        top: 10%;
        width: 200px;
        height: 200px;
        border: 1px solid gray;
        border-radius: 50%;
        overflow: hidden;
        background-size: 100% 100%;
        background-image: url('./images/icon.jpg');
    }
    
    .user_container tbody span {
        cursor: pointer;
    }
    
    .pagination .borderNum {
        font-weight: 700;
    }
    
    .pagination .borderNum a {
        color: #191970;
    }
    
    button .addUser,
    button .findUser {
        background-color: #2CB5AC;
        color: white;
    }
</style>
<div class="user_container">
    <div class="row">
        <div class="col-md-1">
            <button class="btn btn-default addUser" role="button" data-toggle="modal" data-target="#updateUserModal">添加</button>

        </div>
        <div class="col-md-2">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="请输入用户名" aria-describedby="basic-addon1">
            </div>
        </div>
        <div class="col-md-2">
            <select class="form-control user_search_text">
            <option class="val" value="">请选择角色</option>
          
        </select>
        </div>
        <div class="col-md-1">
            <button type="button" class="btn btn-default findUser">搜索</button>
        </div>
        <div class="col-md-6"></div>
    </div>
    <table class="table table-hover">
        <thead>
            <td>序号</td>
            <td>用户名</td>
            <td>姓名</td>
            <td>角色</td>
            <td>性别</td>
            <td>状态</td>
            <td>手机号</td>
            <td>操作</td>
        </thead>
        <tbody></tbody>
    </table>
    <!-- 分页部分 -->
    <nav aria-label="Page navigation">
        <ul class="pagination">
            <li class="lastPage">
                <span aria-hidden="true">&laquo;</span>
                </a>
            </li>

            <li class="role-page nextPage">
                <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        </ul>
    </nav>
    <!--模态框使用-->
    <div class="modal fade" id="updateUserModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="exampleModalLabel">添加用户信息</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="username" class="col-sm-2 control-label">用户名</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="UpUsername" placeholder="用户名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="realname" class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="UpRealname" placeholder="name">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
                            <div class="col-sm-10">
                                <input type="password" class="form-control" id="UpPassword" placeholder="Password">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputPassword3" class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <div class="radio">
                                    <label>
                                    <input type="radio" name="UpGender" id="Upmale" value="male"
                                        >男
                                </label> &nbsp;&nbsp;
                                    <label>
                                    <input type="radio" name="UpGender" id="Upfemale" value="female">
                                    女
                                </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="phone" class="col-sm-2 control-label">手机号</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="UpPhone" placeholder="tel">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="Upbirth" class="col-sm-2 control-label">生日</label>
                            <div class="col-sm-10">
                                <input type="date" class="form-control" id="Upbirth" placeholder="date">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal" id="UpNone">取消</button>
                    <button type="button" class="btn btn-default" id="UpSbmit" data-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>
    <!--模态框结束-->
    <!--设置模态框-->
    <div class="modal fade szmd" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" id="rolModalSet">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="rolModalLabel">设置角色</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="inputEmail3" class="col-sm-2 control-label">用户名</label>
                            <div class="col-sm-10">
                                <input type="email" class="form-control" id="inputEmail3" placeholder="用户名" readonly value="">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputEmail3" class="col-sm-2 control-label">角色</label>
                            <div class="col-sm-10">
                                <label class="checkbox-inline">
                                <input type="checkbox" id="inlineCheckbox1" value="1" > 教师
                            </label>
                                <label class="checkbox-inline">
                                <input type="checkbox" id="inlineCheckbox2" value="2"> 管理员
                            </label>
                                <label class="checkbox-inline">
                                <input type="checkbox" id="inlineCheckbox3" value="6" > 学生
                            </label>
                            </div>

                        </div>




                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal" id="setNone">取消</button>
                    <button type="button" class="btn btn-default submitBtn" data-dismiss="modal" id="setSubmit">确定</button>
                </div>
            </div>
        </div>
    </div>
    <!--设置模态框结束-->
    <!-- 详情模态框 -->
    <!-- Modal -->
    <div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">用户详情</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <h4>用户名：</h4>
                        <div class="detailModal-form detail-username">用户名：</div>
                    </div>
                    <div class="form-group">
                        <h4>姓名：</h4>
                        <div class="detailModal-form detail-realname">姓名</div>
                    </div>
                    <div class="form-group">
                        <h4>手机号：</h4>
                        <div class="detailModal-form detail-phone">手机号</div>
                    </div>
                    <div class="form-group">
                        <h4>性别：</h4>
                        <div class="detailModal-form detail-gender">性别</div>
                    </div>
                    <div class="form-group">
                        <h4>注册时间：</h4>
                        <div class="detailModal-form detail-time">注册时间</div>
                    </div>
                    <div class="form-group">
                        <h4>状态：</h4>
                        <div class="detailModal-form detail-statu">未知状态</div>
                    </div>
                    <div class="detailModal-icon">

                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">确定</button>

                </div>
            </div>
        </div>
    </div>
    <!-- 结束 -->
</div>
<script>
    //声明全局变量
    var baseUrl = "http://47.96.133.125:7788";
    var page = 1;
    var pageSize = 10;
    var username;
    var rolename;
    //通过promise封装函数
    function getData(type, url) {
        var p = new Promise((resolve, reject) => {
            //执行请求
            $.ajax({
                url: url,
                type: type,
                headers: {
                    "Authorization": sessionStorage.getItem("token")
                },
                success: function(res) {
                    resolve(res);
                }
            })
        })
        return p;
    }
    //1.点击进入就发送角色查询请求
    getData("get", baseUrl + "/role/findAll").then(function(res) {
        res.data.forEach((item) => {
            $(".user_container .val").after(`<option>` + item.name + `</option>`);
        });
    });
    //封装数据处理函数,所有的请求函数
    function getUserData(url) {
        return getData('get', baseUrl + url).then(function(res) {
            //清空页面处理
            if ($('.pageNumber').length > 0) {
                $('.pageNumber').remove();
            }
            $(".user_container tbody").empty();
            //追加用户
            var user = res.data.list;
            user.forEach((item, index) => {
                // console.log(item);
                // console.log(JSON.stringify(item));
                $('.user_container tbody').append(`
                          <tr>
                          <td>${index + 1}</td>
                          <td>${item.username}</td>
                          <td>${item.realname}</td>
                          <td>${item.roles.map(function (it) { return it.name }).join()}</td>
                          <td>${item.gender === 'female' ? '女' : '男'}</td>
                          <td>${item.status}</td>
                          <td>${item.telephone}</td>
                          <td>
                          <span data-id="${item.id}" class="setBtn" data-toggle="modal" data-target=".szmd">设置</span>
                          <span data-id="${item.id}" class="delBtn">移除</span>
                          <span data-id="${item.id} " class="moreBtn"data-toggle="modal" data-target="#detailModal">详情</span>
                          <span data-id="${JSON.stringify(item.id)}" class="updateBtn" data-toggle="modal" data-target="#updateUserModal">修改</span></td>
                          </tr>
                          `);
            });

            //分页设置，追加按钮
            pageNum = Math.ceil(res.data.total / pageSize);


            if (page <= 1) {
                $('.user_container .lastPage').addClass("disabled");
            } else {
                $('.user_container .lastPage').removeClass("disabled");
            }
            if (page >= pageNum) {
                $('.user_container .nextPage').addClass("disabled");
            } else {
                $('.user_container .nextPage').removeClass("disabled");
            }
            // console.log(pageNum);
            for (var i = 1; i <= pageNum; i++) {
                $('.user_container .role-page').before(`
                          <li class="pageNumber" value=${i}><a href="#">${i}</a></li>
                          `)
            }
            $('.pagination .pageNumber').removeClass('borderNum');
            $('.pagination .pageNumber[value=' + page + ']').addClass('borderNum');
            //给按钮绑定事件,数字按钮
            $('.pageNumber').click(function() {
                page = $(this).text();
                //判断是否有查询
                var roleUrl = getUrl();
                //发送请求
                getUserData(roleUrl);
            });

            //给操作绑定按钮
            $('.user_container .setBtn').click(function() {
                console.log($(this));
                var id = $(this).attr("data-id");
                var userData = user.filter(function(item) {
                    return item.id == id
                })
                setBtn(userData);
            });
            $('.user_container .delBtn').click(function() {
                var id = $(this).attr("data-id");
                delBtn(id);
            });
            $('.user_container .moreBtn').click(function() {
                var id = $(this).attr("data-id");
                var userData = user.filter(function(item) {
                    return item.id == id
                })
                moreBtn(userData);
            });
            $('.user_container .updateBtn').unbind('click').bind('click', (function() {
                var id = $(this).attr("data-id");
                var userData = user.filter(function(item) {
                    return item.id == id
                })
                updateBtn(userData);
            }))

        })
    }
    //给前后按钮绑定事件
    $('.user_container .lastPage').click(function() {
        page = Number(page);
        if ((page - 1) >= 1) {
            page--;
        }
        //判断是否有查询
        console.log(page);
        var roleUrl = getUrl();
        //发送请求
        getUserData(roleUrl);

    });
    $('.user_container .nextPage').click(function() {
        page = Number(page);
        if ((page + 1) <= pageNum) {
            page++;
        }
        console.log(page);
        //判断是否有查询
        var roleUrl = getUrl();
        //发送请求
        getUserData(roleUrl);

    })
    getUserData('/baseUser/pageQuery?page=' + page + '&pageSize=' + pageSize);
    //给搜索按钮绑定事件
    $('.user_container .findUser').click(function() {
            username = $('.user_container input').val();
            rolename = $('.user_container select').val();
            // console.log(rolename);
            // console.log(username);
            // console.log(pageSize);
            page = 1;
            var url = getUrl();
            getUserData(url);
        })
        //封装获取地址函数
    function getUrl() {
        var result;
        if (username || rolename) {
            if (!rolename) {
                result = "/baseUser/pageQuery?page=" + page + "&pageSize=" + pageSize + " &username=" + username;
                console.log("no rolename", username);
            } else if (!username) {
                result = "/baseUser/pageQuery?page=" + page + "&pageSize=" + pageSize + " &rolename=" + rolename;
                console.log("no username", rolename);
            } else {
                result = "/baseUser/pageQuery?page=" + page + "&pageSize=" + pageSize + " &username=" + username + "&rolename=" + rolename;
                console.log(rolename, username);
            }
        } else {
            result = "/baseUser/pageQuery?page=" + page + "&pageSize=" + pageSize;
            console.log("no ");
        }
        return result;
    }
    //操作函数
    //设置函数
    function setBtn(userData) {
        console.log(userData);
        //清空勾选框
        $('#rolModalSet input[type=checkbox]').prop('checked', false);
        var role = userData[0].roles.map(function(it) {
            return it.id
        }).join();
        var id = userData[0].id;
        console.log(role);
        // console.log(id);
        if (role.indexOf("1") != (-1)) {
            $('#rolModalSet #inlineCheckbox1').prop('checked', true);
        };
        if (role.indexOf("2") != (-1)) {
            $('#rolModalSet #inlineCheckbox2').prop('checked', true);
        };
        if (role.indexOf("6") != (-1)) {
            $('#rolModalSet #inlineCheckbox3').prop('checked', true);
        };
        if (role.length == 0) {
            $('#rolModalSet #inlineCheckbox3').prop('checked', true);
            console.log(1);
        }
        $('#rolModalSet #inputEmail3').val(userData[0].username);
        // console.log($('.user_container #rolModalSet #setSubmit'));
        //确定按钮绑定
        $('#rolModalSet .submitBtn').click(() => {
            console.log(id);
            // var role = $('#rolModalSet input:checkbox:checked');
            var ids = [];
            $('#rolModalSet input:checkbox:checked').map(function(index, item) {
                console.log('遍历勾选');
                ids.push($(item).val());
            });

            console.log(ids);
            getData("post", baseUrl + "/baseUser/setRoles?roles=" + ids + "&id=" + id).then(function(res) {
                console.log(res);
                // $('.user_container .setBtn').bind('click');
                getUserData('/baseUser/pageQuery?page=' + page + '&pageSize=' + pageSize);
                $('.user_container #rolModalSet #setSubmit').unbind('click');
                $('.user_container #rolModalSet #setNone').unbind('click');
            });
            //清除绑定事件
        })
        $('.user_container #rolModalSet #setNone').click(() => {
            $('.user_container #rolModalSet #setSubmit').unbind('click');
            $('.user_container #rolModalSet #setNone').unbind('click');
        })

    }
    //删除函数 input[id=inputEmail3]
    function delBtn(id) {
        console.log(id);
        if (confirm("是否永久删除？")) {
            $.ajax({
                url: baseUrl + "/baseUser/deleteById",
                type: "get",
                data: {
                    id: id
                },
                headers: {
                    "Authorization": sessionStorage.getItem("token")
                },
                success(res) {
                    alert("删除成功");
                    getUserData('/baseUser/pageQuery?page=' + page + '&pageSize=' + pageSize);
                },
                error(err) {
                    console.log(err);
                }
            })
        }
    };
    //详情函数
    function moreBtn(userData) {
        console.log(userData);
        //判断男女
        var gender;
        if (userData[0].gender == 'male') {
            gender = "男";
        } else if (userData[0].gender == 'female') {
            gender = '女';
        } else {
            gender = '未知';
        }
        //将时间转换为年月日格式
        var unixTimestamp = null;
        var commonTime;
        if (userData[0].registerTime != null) {
            unixTimestamp = new Date(userData[0].registerTime);
        }
        if (unixTimestamp != null) {
            commonTime = unixTimestamp.toLocaleString();
        } else {
            commonTime = '未知';
        }
        // console.log($('.detail-username').text());
        $('.detail-username').text(userData[0].username);
        $('.detail-realname').text(userData[0].realname);
        $('.detail-phone').text(userData[0].telephone);
        $('.detail-gender').text(gender);
        $('.detail-time').text(commonTime);
        $('.detail-statu').text(userData[0].status);

    }
    //修改函数
    function updateBtn(userData) {
        console.log(userData);

        //判断生日
        var birth;
        var unixTimestamp = null;
        // console.log(userData[0].birth);
        if (userData[0].birth != null) {
            unixTimestamp = new Date(userData[0].birth);
        }
        if (unixTimestamp != null) {
            birth = getBirth(unixTimestamp);
        } else {
            birth = null;
        }
        //将数据回显
        $('.user_container #exampleModalLabel').text('修改用户信息');
        $('.user_container #updateUserModal #UpUsername').val(userData[0].username);
        $('.user_container #updateUserModal #UpRealname').val(userData[0].realname);
        $('.user_container #updateUserModal #UpPassword').val(userData[0].password);
        $('.user_container #updateUserModal input[type=radio][value=' + userData[0].gender +
            ']').prop('checked', true);
        $('.user_container #updateUserModal #UpPhone').val(userData[0].telephone);
        $('.user_container #updateUserModal #Upbirth').val(birth);

        //给确定按钮绑定事件
        $('.user_container #updateUserModal #UpSbmit').click(() => {
            var userName = $('.user_container #updateUserModal #UpUsername').val();
            var realName = $('.user_container #updateUserModal #UpRealname').val();
            var password = $('.user_container #updateUserModal #UpPassword').val();
            var gender = $('.user_container #updateUserModal input[type=radio]:checked').val();
            var phone = $('.user_container #updateUserModal #UpPhone').val();
            var temp = $('.user_container #updateUserModal #Upbirth').val();
            var birth;
            var userid = userData[0].id;
            //将毫秒事件转换为毫秒
            if (temp != '') {
                var data = new Date(temp);
                birth = data.getTime().toString();
            } else {
                birth = '';
            }
            console.log(userid, userName, realName, password, gender, phone, birth);
            //发送请求
            getData("post", baseUrl + '/baseUser/saveOrUpdate?id=' + userid + '&username=' + userName + '&password=' + password + '&telephone=' + phone + '&realname=' + realName + '&gender=' + gender + '&birth=' + birth + '&status=正常').then(function(res) {
                    // console.log(userid);
                    console.log(res);
                    getUserData('/baseUser/pageQuery?page=' + page + '&pageSize=' + pageSize);
                })
                //清除绑定事件
            $('.user_container #updateUserModal #UpSbmit').unbind('click');
            $('.user_container #updateUserModal #UpNone').unbind('click');
        })
        $('.user_container #updateUserModal #UpNone').click(() => {
            $('.user_container #updateUserModal #UpSbmit').unbind('click');
            $('.user_container #updateUserModal #UpNone').unbind('click');
        })

    }
    //获取生日函数
    function getBirth(date) {
        //获取年份
        var year = date.getFullYear();
        //获取月份返回
        var month = date.getMonth() + 1;
        //获取日
        var day = date.getDate();
        return year + '-' + addZero(month) + '-' + addZero(day);
    }

    function addZero(num) {
        return num < 10 ? '0' + num : num;
    }
    //给新增按钮绑定监听
    $('.user_container .addUser').click(() => {
        $('.user_container #updateUserModal input[type = text]').val('');
        $('.user_container #updateUserModal input[type = password]').val('');
        $('.user_container #updateUserModal #exampleModalLabel').text('新增用户');
        $('.user_container #updateUserModal #UpSbmit').click(() => {
            //获取用户输入内容
            var userName = $('.user_container #updateUserModal #UpUsername').val();
            var realName = $('.user_container #updateUserModal #UpRealname').val();
            var password = $('.user_container #updateUserModal #UpPassword').val();
            var gender = $('.user_container #updateUserModal input[type=radio]:checked').val();
            var phone = $('.user_container #updateUserModal #UpPhone').val();
            var temp = $('.user_container #updateUserModal #Upbirth').val();
            var birth;
            //将日期转为毫秒
            if (temp != '') {
                var data = new Date(temp);
                birth = data.getTime().toString();
            } else {
                birth = '';
            }
            console.log(userName, realName, password, gender, phone, birth);
            //发送请求
            getData("post", baseUrl + '/baseUser/saveOrUpdate?&username=' + userName + '&password=' + password + '&telephone=' + phone + '&realname=' + realName + '&gender=' + gender + '&birth=' + birth + '&status=正常').then(function(res) {
                // console.log(userid);
                console.log(res);
                getUserData('/baseUser/pageQuery?page=' + page + '&pageSize=' + pageSize);
                $('.user_container #updateUserModal #UpSbmit').unbind('click');
                $('.user_container #updateUserModal #UpNone').unbind('click');
            });
            //清除事件
            $('.user_container #updateUserModal #UpNone').click(() => {
                $('.user_container #updateUserModal #UpSbmit').unbind('click');
                $('.user_container #updateUserModal #UpNone').unbind('click');
            });

        })
    })
</script>